/**
 * Created by jt on 2017/5/6.
 */
import "./index.less";
import {qotCntTyp,currTyp,dpstFlg,pubPriFlg} from "../config.js";
import "../../../unit/common/js/bootstrap_js/jquery.jqGrid.src.js";

import chooseSupTpl from "./chooseSup.handlebars";
import proInfoTpl from "./proInfo.handlebars";
import setTableTpl from "./set_table.handlebars";

jQuery(function () {
    App.init();
    var token = sessionStorage.getItem('token');
    var projId = getArgs().id;
    var currTyp = {};    // 币种  key:value
    var currVal = {};    // 汇率  key:value
    var currrTypList = [];
    var projSts = '';
    var disAgreedNum = 0;
    var collectGrdInf = {};
    var matlList = [];
    var grdRul = '0';  // 最低单价中标
    var awdResList = {"0":"未审核","1":"同意","2":"不同意"};
    var colapsedRow = [];  // 保存已选中的数据行信息

    if (token == null || token =='') {
        location.href = HOST_FRT+'/logins/login.html';
    }
    jQuery('.logOut').attr('href','../logins/login.html');

    // 排序
    function sortBy (property){
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    }

    // 获取专家评标汇总信息
    $.ajax({
        url: HOST_ADDR + '/cpmp/bidProjOnMngForPchs/collectGrdInf/'+projId,
        type: 'get',
        async: false,
        dataType: 'json',
        headers: {
            'access_token': token,'login_type':'ums'
        },
        contentType: "application/json",
        success: function (resp) {
            if (resp.success) {
                console.log(resp);
                collectGrdInf = resp.data;
                // if(typeof(resp.data.projInf.grdRul)!='undefined' && resp.data.projInf.grdRul!=null && resp.data.projInf.grdRul!=''){
                //     self.grdRul = resp.data.projInf.grdRul;
                // }
                // if(typeof(resp.data.projInf.matDtls)!='undefined' && resp.data.projInf.matDtls!=null && resp.data.projInf.matDtls!=''){
                //     self.matDtls = resp.data.matDtls;
                // }
                // self.exptNams = resp.data.exptNams;
                // self.exptGrdList = resp.data.list;
                // self.renderResultList();
            }
            else {
                alert(resp.msgInf);
            }
        },
        error: function (err) {
            console.log(err);
        }
    });


     // 查询供应商报价信息
    jQuery.ajax({
        url: HOST_ADDR + `/cpmp/bidProjOnMngForPchs/getAppAwdInf/`+projId,
        type: 'get',
        dataType: 'json',
        headers: {
            'access_token': token,'login_type':'ums'
        },
        contentType: "application/json",
        success: function (resp) {
            if (!resp.success) {
                console.log(resp.msgCod+' '+resp.msgInf);
                return;
            }
            console.log(resp);
            showTableData(resp.data.appAwdInfDtls);
            setTimeout(resetGridTable,2000);
            resp.data.bidProjOn.qotCntTypFmt = qotCntTyp[resp.data.bidProjOn.qotCntTyp] || '';
            resp.data.bidProjOn.currTypFmt = currTyp[resp.data.bidProjOn.currTyp] || '';
            resp.data.bidProjOn.dpstFlgFmt = dpstFlg[resp.data.bidProjOn.dpstFlg] || '';
            resp.data.bidProjOn.pubPriFlgFmt = pubPriFlg[resp.data.bidProjOn.pubPriFlg] || '';
            if(resp.data.matTypDesc!=null && resp.data.matTypDesc!=''){
                resp.data.bidProjOn.matTyp = resp.data.matTypDesc;
            }
            $(".projNam span").html(resp.data.bidProjOn.projNam);
            $(".projNbr span").html(resp.data.bidProjOn.projNbr);
            $(".bidDptAddr span").html(resp.data.bidProjOn.bidDptAddr);
            $(".bidOpenTim span").html((new Date(resp.data.bidProjOn.bidOpenTim)).Format("yyyy-MM-dd hh:mm"));
            grdRul = resp.data.bidProjOn.grdRul ? resp.data.bidProjOn.grdRul : '0';
            showTableDataList(resp.data.appAwdInfDtls);
            // projSts = resp.data.bidProjOn.projSts;
            // $(".proInfo").removeClass("hide");
            // $(".expCheck").removeClass("hide");
            // $(".subCheck").addClass("hide");
            // if(projSts=='24'){
            //     $(".proInfo").removeClass("hide");
            //     $(".expCheck").removeClass("hide");
            //     $(".subCheck").addClass("hide");
            //     showTableDataList(resp.data.appAwdInfDtls);
            // }else if(projSts=='25'){ // 查看提交给专家的定标结果
            //     $(".expCheck").addClass("hide");
            //     $(".subCheck").removeClass("hide");
            //     $(".resInfo").removeClass("hide");
            //     showResultTable(resp.data);
            //     getExptAwdRes();
            // }

        },
        error: function (err) {
            console.log(err);
        }
    });


    var submitFlg = true;
    //提交BPM审核    // 提交专家审核
    jQuery('.submit.subCheck').click(function () {
        var url='';
        var successMsg = '';
        var appAwdDtls = [];
        url = HOST_ADDR+'/cpmp/bidProjOnMngForPchs/appAwd';
        successMsg = '申请定标成功！';
        console.log("******提交BPM审核*******");
        if(!submitFlg){
            setTimeout(function(){submitFlg = true;},5000);
        }
        // if($(this).hasClass("subCheck")){ // 提交BPM审核
            // if(disAgreedNum>0){
            //     alert("还有"+disAgreedNum+"位专家没有确认，不允许提交BPM审核！");
            //     return false;
            // }
        // }else if($(this).hasClass("expCheck")){  // 提交专家审核
        //     url = HOST_ADDR+'/cpmp/bidProjOnMngForPchs/sendAwdToExpt';
        //     successMsg = '提交成功，请联系专家确认！';
        //     console.log("******提交专家审核******");
        // }
        var tmpAwdDtls = getPostDatas();
        for(var i=0;i<tmpAwdDtls.length;i++){
            var appAwdDtlInfo = {};
            appAwdDtlInfo.matId = tmpAwdDtls[i].matId;
            appAwdDtlInfo.currTyp = tmpAwdDtls[i].currTyp;
            appAwdDtlInfo.exRat = tmpAwdDtls[i].exRat;
            appAwdDtlInfo.matBnd = tmpAwdDtls[i].matBnd;
            appAwdDtlInfo.matCod = tmpAwdDtls[i].matCod;
            appAwdDtlInfo.memo = tmpAwdDtls[i].memo;
            appAwdDtlInfo.pchsNum = tmpAwdDtls[i].splNum;
            appAwdDtlInfo.splrId = tmpAwdDtls[i].splrId;
            appAwdDtlInfo.splrNam = tmpAwdDtls[i].fullNam;
            appAwdDtlInfo.tendDlvDteStr = tmpAwdDtls[i].tendDlvDte+" 00:00:00";
            appAwdDtlInfo.ttlPri = tmpAwdDtls[i].ttlPriFmt;
            appAwdDtlInfo.untPri = tmpAwdDtls[i].untPri;
            appAwdDtls.push(appAwdDtlInfo);
        }
        // var count = jQuery('.chooseSup input[type="checkbox"]').length;

        var data = {
            "projId":projId,
            "appAwdMemo":"申请决标",
            "appAwdDtls":appAwdDtls
        };
        console.log(data);

        $("#myModal table tbody").html("");
        $('#myModal').modal('show');
        $.each(matlList,function(index,item){
            var lines = 0;
            var splrInfoList = [];
            $.each(appAwdDtls,function(idx,itm){
                if(itm.matId==item.id){
                    splrInfoList.push('<td>'+itm.splrNam+'</td><td>'+itm.untPri+'</td><td>'+itm.pchsNum+'</td><td>'+itm.ttlPri+'</td></tr>');
                    lines++;
                }
            })
            var dlvDate = item.dlvDte ? (new Date(item.dlvDte)).Format("yyyy-MM-dd") : '';
            var basehtml='<tr><td rowspan="'+lines+'">'+item.matNam+'</td><td rowspan="'+lines+'">'+item.matCod+'</td><td rowspan="'+lines+'">'+item.dlvAdr+'</td><td rowspan="'+lines+'">'+dlvDate+'</td><td rowspan="'+lines+'">'+item.pchsNum+'</td>';
            var beginhtml = '<tr>';
            var endhtml = '<td></td><td></td><td></td><td></td></tr>';
            if(lines){
                $.each(splrInfoList,function(idx1,val){
                    if(idx1==0){
                        $("#myModal table tbody").append(basehtml+val);
                    }else{
                        $("#myModal table tbody").append(beginhtml+val);
                    }
                });
            }else{
                $("#myModal table tbody").append(basehtml+endhtml);
            }
        });

        $("#myModal .retn.submit").on("click",function(){
            $('#myModal').modal('hide');
        });

        $("#myModal .green.submit").on("click",function(){
            if(!submitFlg){
                return false;
            }
            submitFlg = false;
            jQuery.ajax({
                url: url,
                type: 'post',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType:"application/json",
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                success: function(resp){
                    if (!resp.success) {
                        alert(resp.msgCod+' '+resp.msgInf);
                        return;
                    }
                    console.log(resp);
                    alert(successMsg);
                    submitFlg = true;
                    location.href = '/bid_online/proj_list.html';
                },
                error:function(err){
                    alert('系统错误！');
                }
            });
        });
    });


    // // 检查专家审批结果
    // function checkAwdRes(){
    //     var flg = true;
    //     $(".exptResList tr").each(function(){
    //         if($(this).find(".isAgreed").attr("isAgreed")!='1'){
    //             alert("所有专家必须审核通过后才可以提交BPM审核！");
    //             flg = false;
    //             return flg;
    //         }
    //     });
    //     return flg;
    // }
    //
    //
    // // 获取专家审批结果
    // function getExptAwdRes(){
    //     jQuery.ajax({
    //         url: HOST_ADDR + '/cpmp/bidProjOnMngForPchs/getExptAwdRes/'+projId,
    //         type: 'get',
    //         dataType: 'json',
    //         contentType:"application/json",
    //         headers: {
    //             'access_token': token,'login_type':'ums'
    //         },
    //         success: function(resp){
    //             if (!resp.success) {
    //                 alert(resp.msgCod+' '+resp.msgInf);
    //                 return;
    //             }else{
    //                 if(resp.data.length){
    //                     $.each(resp.data,function(index,item){
    //                         item.isAgreed!='1' && disAgreedNum++;
    //                         var result = awdResList[item.isAgreed] || "未知状态";
    //                         var rsn = item.projAwdRsn != null ? item.projAwdRsn : '';
    //                         var opera = item.isAgreed=='2' ? '<button class="btn mini blue changeRes" grdId="'+item.grdId+'">重新审批</button>':"";
    //                         var html = '<tr grdId="'+item.grdId+'"><td class="exptNam">'+item.exptNam+'</td><td class="isAgreed" isAgreed="'+item.isAgreed+'">'+result+'</td><td class="rsn">'+rsn+'</td><td class="opera">'+opera+'</td></tr>';
    //                         $(".exptResList").append(html);
    //                     });
    //                     addBindEvent();
    //                 }
    //             }
    //             console.log(resp);
    //         },
    //         error:function(err){
    //             alert('系统错误！');
    //         }
    //     });
    // }

    // 给动态添加的元素绑定点击事件
    function addBindEvent(){
        // 修改专家审批状态
        // $(".changeRes").on("click",function(){
        //     var tmpGrdId = $(this).attr("grdId");
        //     jQuery.ajax({
        //         url: HOST_ADDR + '/cpmp/bidProjOnMngForPchs/updateExptAppRes/' + tmpGrdId,
        //         type: 'get',
        //         dataType: 'json',
        //         contentType: "application/json",
        //         headers: {
        //             'access_token': token, 'login_type': 'ums'
        //         },
        //         success: function (resp) {
        //             if (!resp.success) {
        //                 alert(resp.msgCod + ' ' + resp.msgInf);
        //                 return;
        //             } else {
        //                 alert(resp.msgCod + ' ' + resp.msgInf);
        //                 $(".exptResList tr[grdId="+tmpGrdId+"]").find(".isAgreed").html("未审批").attr("isAgreed","0");
        //                 $(".exptResList tr[grdId="+tmpGrdId+"]").find(".rsn").html("");
        //                 $(".exptResList tr[grdId="+tmpGrdId+"]").find(".opera").html("");
        //             }
        //         },
        //         error: function (err) {
        //             alert('系统错误！');
        //         }
        //     });
        // });
    }

    // 表头供应商报价信息
    function showTableData(datalist){
        var colNames = ["物料编码","物料名称","交货地址","交货日期"];
        var splrlists = [];
        var rows = [];   // 所有行数据
        var groupHeaders = [];
        var colModel = [
            {name:"matCod",index:"matCod",align:'left',width : 80,sortable : false},
            {name:"matNam",index:"matNam",align:'left',width : 120,sortable : false},
            {name:"dlvAdr",index:"dlvAdr",align:'center',width : 120,sortable : false},
            {name:"dlvDteStr",index:"dlvDteStr",align:'center',width : 100,sortable : false}
        ];
        if(datalist.length){
            if(typeof(datalist[0].qotDtls) != 'undefined' && datalist[0].qotDtls.length){
                var allQotSplrList = [];     // 所有参与报价的供应商
                var allSplrIds = [];
                for(var a=0;a<datalist.length;a++){
                    var tmpSplrInfoList = datalist[a].qotDtls;
                    for(var b=0;b<tmpSplrInfoList.length;b++){
                        if(allSplrIds.indexOf(tmpSplrInfoList[b].splrId)==-1){  // 数组中不存在的时候，添加
                            allSplrIds.push(tmpSplrInfoList[b].splrId);
                            allQotSplrList.push({"splrId":tmpSplrInfoList[b].splrId,"fullNam":tmpSplrInfoList[b].fullNam});
                        }
                    }
                }

                for(var i=0; i< allQotSplrList.length; i++){
                    splrlists.push({"splrId":allQotSplrList[i].splrId,"name":allQotSplrList[i].fullNam}); // 参与报价的供应商列表,"单价","数量","币种"
                    groupHeaders.push({startColumnName:"price"+i,numberOfColumns:3,titleText:allQotSplrList[i].fullNam});
                    colNames.push("单价");
                    colNames.push("数量");
                    colNames.push("币种");
                    colModel.push({name:"price"+i,index:"price"+i,align:'center',width : 60,sortable : false});
                    colModel.push({name:"splNum"+i,index:"splNum"+i,align:'center',width : 60,sortable : false});
                    colModel.push({name:"currTyp"+i,index:"currTyp"+i,align:'center',width : 60,sortable : false,formatter: currTypFmatter});
                }
            }else{
                alert("数据异常！");
            }
        }

        for(var j=0;j<datalist.length;j++){
            var tmprow = {};
            tmprow.matCod = datalist[j].matDtl.matCod;
            tmprow.matNam = datalist[j].matDtl.matNam;
            tmprow.dlvAdr = datalist[j].matDtl.dlvAdr ? datalist[j].matDtl.dlvAdr : '';
            tmprow.dlvDteStr = datalist[j].matDtl.dlvDte ? (new Date(datalist[j].matDtl.dlvDte)).Format("yyyy-MM-dd") : '';
            for(var k=0;k<splrlists.length;k++){
                for(var m=0;m<datalist[j].qotDtls.length;m++){
                    if(splrlists[k].splrId==datalist[j].qotDtls[m].splrId){
                        tmprow["price"+k] = datalist[j].qotDtls[m].untPri;
                        tmprow["splNum"+k] = datalist[j].qotDtls[m].splNum;
                        tmprow["currTyp"+k] = datalist[j].qotDtls[m].currTyp ? datalist[j].qotDtls[m].currTyp : '';
                    }
                }
            }
            rows.push(tmprow);
        }

        $("#mygrid").jqGrid({
            width:'100%',
            dataType:'local',
            colNames:colNames,
            colModel:colModel,
            viewrecords:true,
            rowNum:-1,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true
        });
        $("#mygrid").jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders:groupHeaders
        });

        for ( var i = 0; i < rows.length; i++){
            $("#mygrid").jqGrid('addRowData', i + 1, rows[i]);
        }
        if($("#mygrid").width()< $(".qotinfo").width()){
            $("#mygrid").jqGrid('setGridWidth', $(".qotinfo").width()-4);
        }
    }

    function currTypFmatter(cellvalue, options, rowObject){
        if(typeof(cellvalue)=='undefined' || cellvalue==""){
            return "";
        }
        if(currrTypList.length){
            return currTyp[cellvalue];
        }else{
            var parmTyps = 'CURR_TYP';
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByParmTyp/' + parmTyps,
                type: 'get',
                dataType: 'json',
                async: false,
                headers: {'access_token': token, 'login_type': 'ums'},
                contentType: 'application/json',
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + " - " + resp.msgInf);
                        console.log(resp.msgCod + " - " + resp.msgInf);
                        return;
                    }
                    if (jQuery.isArray(resp.data)) {
                        for (var i = 0; i < resp.data.length; i++) {
                            currrTypList.push(resp.data[i].parmCod);
                            currTyp[resp.data[i].parmCod] = resp.data[i].parmMemo;
                            currVal[resp.data[i].parmCod] = resp.data[i].parmVal;
                        }
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            })
            return currTyp[cellvalue];
        }

    }


    // 物料信息，报价信息表格
    function showTableDataList(datalist){
        var matinfo = [];
        var totalLines = 1;  // 总数据行
        for(var i=0;i<datalist.length;i++){
            matlList.push(datalist[i].matDtl);
            totalLines+=2;
            var tmpQotDtls = [];
            var splrSort = [];  // 供应商综合排名信息
            if(grdRul=='0'){ // 最低单价中标
                if(collectGrdInf.list!=null){
                    $.each(collectGrdInf.list,function(index,item){
                        if(item.matId==datalist[i].matDtl.id){   // 当前物料下面
                            $.each(item.grdInfs,function(idx,val){
                                var tmpSplrInfo = val;
                                var sumScore = 0;
                                $.each(val.grdList,function(idx1,val1){
                                    sumScore += val1.grdOrd ? parseInt(val1.grdOrd) : 1;
                                });
                                tmpSplrInfo["sumScore"] = sumScore;
                                splrSort.push(tmpSplrInfo);
                            });
                        }
                    });
                }
            }else if(grdRul=='2'){ //最低总价中标
                if(collectGrdInf.list!=null){
                    $.each(collectGrdInf.list,function(index,item){
                        var tmpSplrInfo = item;
                        var sumScore = 0;
                        $.each(tmpSplrInfo.grdInfs,function(idx,val){
                            sumScore += val.grdOrd ? parseInt(val.grdOrd) : 1;
                        });
                        tmpSplrInfo["sumScore"] = sumScore;
                        splrSort.push(tmpSplrInfo);
                    });
                }
            }
            console.log(i,splrSort);
            for(var m=0;m<datalist[i].qotDtls.length;m++){
                totalLines+=1;
                var rowinfo = datalist[i].qotDtls[m];
                rowinfo.id = m+1;
                // rowinfo.checked = m==0 ? 1 : 0;
                rowinfo.isLowest = m==0 ? '是' : '';
                rowinfo.tendDlvDte = rowinfo.tendDlvDte ? (new Date(rowinfo.tendDlvDte)).Format("yyyy-MM-dd") : '';
                rowinfo.currTypFmt = rowinfo.currTyp ? rowinfo.currTyp : '';
                rowinfo.exRat = rowinfo.currTyp ? currVal[rowinfo.currTyp] : currTyp[0];
                rowinfo.ttlPriFmt = (parseFloat(rowinfo.untPri) * parseFloat(rowinfo.splNum)).toFixed(2);
                if(splrSort.length){
                    $.each(splrSort,function(index,item){
                        if(rowinfo.splrId==item.splrId){
                            rowinfo.sumScore = item.sumScore;
                        }
                    });
                }else{
                    rowinfo.sumScore = m+1;
                }
                tmpQotDtls.push(rowinfo);
            }
            tmpQotDtls.sort(sortBy("sumScore"));
            $.each(tmpQotDtls,function(index,item){
                item.checked = index==0 ? 1 : 0;
            });
            datalist[i].matDtl.qotDtls = tmpQotDtls;
            matinfo.push(datalist[i].matDtl);
        }
        jQuery("#mygrid2").jqGrid({
            width:'100%',
            dataType:'local',
            width:'100%',
            height: 250,
            colNames:['ID','物料编码','物料名称', '计量单位', '招标数量','交货地址','交货日期','备注'],
            colModel:[
                {name:'id',index:'id', width:50,hidden: true},
                {name:'matCod',index:'matCod', width:80},
                {name:'matNam',index:'matNam', width:150},
                {name:'matUnt',index:'matUnt', width:80,align:"center"},
                {name:'pchsNum',index:'pchsNum', width:80,align:"center"},
                {name:'dlvAdr',index:'dlvAdr', width:80},
                {name:'dlvDte',index:'dlvDte', width:120,align:"center"},
                {name:'memo',index:'memo', width:150}
            ],
            multiselect: false,
            subGrid: true,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            // define the icons in subgrid
            subGridOptions: {
                "plusicon"  : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon"  : "ui-icon-arrowreturn-1-e",
                "reloadOnExpand" : true,
                "selectOnExpand" : true
            },
            subGridRowColapsed:function(subgrid_id, row_id){
                var subgrid_table_id = subgrid_id+"_t";
                if($("#"+subgrid_table_id)[0].p.savedRow.length){
                    $("#"+subgrid_table_id).jqGrid("saveCell", $("#"+subgrid_table_id)[0].p.savedRow[0].id, $("#"+subgrid_table_id)[0].p.savedRow[0].ic)
                }
                var subids = $("#"+subgrid_table_id).jqGrid('getGridParam','selarrrow');  // 选择的行
                for(var m=0;m<matinfo[row_id-1].qotDtls.length;m++){
                    var subrowid = m+1;
                    var rowinfo = matinfo[row_id-1].qotDtls[m];
                    if(subids.length && subids.indexOf(subrowid+"")>=0){    // 记录选择的状态
                        rowinfo.checked = 1;
                        var dataObj = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid);
                        colapsedRow.push(dataObj);     // 保存已选择的行数据
                    }else{
                        rowinfo.checked = 0;
                    }
                    rowinfo.id = subrowid;
                    rowinfo.splNum = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).splNum;
                    rowinfo.ttlPriFmt = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).ttlPriFmt;
                    rowinfo.memo = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).memo;
                }
            },
            subGridRowExpanded: function(subgrid_id, row_id) {
                var subgrid_table_id, pager_id, lastsel;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;
                $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
                jQuery("#"+subgrid_table_id).jqGrid({
                    datatype: "local",
                    height: '100%',
                    colNames: ['matId','供应商ID','供应商','是否最低价','综合排名','币种','币种hidden','汇率','投标价格','应标数量','合计','应标交货日期','品牌','备注'],
                    colModel: [
                        {name:"matId",index:"matId",hidden:true},
                        {name:"splrId",index:"splrId",hidden:true},
                        {name:"fullNam",index:"fullNam",width:200, sortable:false},
                        {name:"isLowest",index:"isLowest",width:70, sortable:false},
                        {name:"allOrd",index:"allOrd",width:70,align:"center", sortable:false},
                        {name:"currTypFmt",index:"currTypFmt",width:70,align:"center", sortable:false,formatter: currTypFmatter},
                        {name:"currTyp",index:"currTyp",hidden:true},
                        {name:"exRat",index:"exRat",hidden:true},
                        {name:"untPri",index:"untPri",width:80,align:"center", sortable:false},
                        {name:"splNum",index:"splNum",width:80,align:"center", classes:"splNum",sortable:false, formatter:'number',classes:"editable",editable:true,editrules:{number:true}},
                        {name:"ttlPriFmt",index:"ttlPriFmt",width:90,align:"center", sortable:false},
                        {name:"tendDlvDte",index:"tendDlvDte",width:120,align:"center", sortable:false},
                        {name:"matBnd",index:"matBnd",width:80,align:"center", sortable:false},
                        {name:"memo",index:"memo",width:100,align:"center", sortable:false,classes:"editable",editable:true}
                    ],
                    fitColumns: true,
                    shrinkToFit: true,
                    altRows: true,
                    multiselect: true,
                    cellEdit: true,
                    cellsubmit: 'clientArray',
                    onSelectRow : function(id) {
                        if (id && id !== lastsel) {
                            jQuery("#"+subgrid_table_id).jqGrid('saveRow', lastsel);
                            lastsel = id;
                        }
                    },
                    afterEditCell: function(a, b, c, d, e) { },
                    formatCell: function(a, b, c, d, e) { },
                    beforeSubmitCell: function(a, b, c, d, e) { },
                    beforeSaveCell: function(a, b, c, d, e) {
                        var rowinfo = $("#"+subgrid_table_id+" #"+a).data("rowinfo");
                        if(b=="splNum" &&(isNaN(c) || c == '')){
                            c = rowinfo.splNum;
                        }
                        return c;
                    },
                    afterSaveCell: function(a, b, c, d, e) {
                        console.log('afterSaveCell',a, b, c, d, e);
                        var f = $("#"+subgrid_table_id).jqGrid("getRowData", a);
                        if(b=="splNum" || b=="untPri"){
                            var splNum = parseFloat(f.splNum);
                            var untPri = parseFloat(f.untPri);
                            var ttlPriFmt = (splNum*untPri).toFixed(2);
                            console.log(splNum,untPri,ttlPriFmt);
                            $("#"+subgrid_table_id).jqGrid("setRowData", a, {ttlPriFmt: ttlPriFmt});
                        }
                    }
                });
                for(var m=0;m<matinfo[row_id-1].qotDtls.length;m++){
                    var subrowid = m+1;
                    var rowinfo = matinfo[row_id-1].qotDtls[m];
                    rowinfo.allOrd = m+1;
                    rowinfo.id = subrowid;
                    // rowinfo.tendDlvDte = rowinfo.tendDlvDte ? (new Date(rowinfo.tendDlvDte)).Format("yyyy-MM-dd") : '';
                    // rowinfo.currTypFmt = rowinfo.currTyp ? rowinfo.currTyp : '';
                    // rowinfo.exRat = rowinfo.currTyp ? currVal[rowinfo.currTyp] : currTyp[0];
                    // rowinfo.ttlPriFmt = (parseFloat(rowinfo.untPri) * parseFloat(rowinfo.splNum)).toFixed(2);
                    $("#"+subgrid_table_id).jqGrid('addRowData', subrowid, rowinfo);
                    $("#"+subgrid_table_id+" #"+subrowid).data("rowinfo",rowinfo);
                    if(rowinfo.checked){
                        $("#"+subgrid_table_id).jqGrid('setSelection',subrowid);   // 选中
                        if(colapsedRow.length){
                            for(var k=0,flag=true,len=colapsedRow.length;k<len;flag ? k++ : k){
                                if( colapsedRow[k]&&colapsedRow[k].matId==rowinfo.matId && colapsedRow[k].splrId==rowinfo.splrId){
                                    colapsedRow.splice(k,1);
                                    flag = false;
                                } else {
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
        });
        for ( var i = 0; i < matinfo.length; i++){
            var rowid = i+1;
            matinfo[i].dlvDte = matinfo[i].dlvDte ? (new Date(matinfo[i].dlvDte)).Format("yyyy-MM-dd") : '';
            $("#mygrid2").jqGrid('addRowData', rowid, matinfo[i]);
            $("#mygrid2>tbody>tr#"+rowid+">td").trigger("click");  // 报价信息展开
            if($("#mygrid2_"+rowid+"_t").width()+27<$(".qotinfo2").width()){
                $("#mygrid2_"+rowid+"_t").jqGrid('setGridWidth', $(".qotinfo2").width()-27);
            }
        }
        jQuery("#mygrid2").jqGrid('setGridWidth', $("#mygrid2_1_t").width()+27);
        jQuery("#mygrid2").jqGrid('setGridHeight', totalLines*30+3*(matinfo.length+1));
        $("#mygrid2>tbody>tr.jqgrow").addClass("bg-lightgray");
        rendinfo();
    }

    // 定标结果展示
    function showResultTable(data){
        var matinfo = [];
        $.each(data.appAwdInfDtls,function(index,item){
            matinfo.push(item.matDtl);
        });
        var bidSplrList = data.winDtls;
        var totalLines = 1;  // 总数据行
        for(var i=0;i<matinfo.length;i++){
            totalLines+=2;
            var qotDtl = [];
            for(var m=0;m<bidSplrList.length;m++){
                if(bidSplrList[m].matId==matinfo[i].id){
                    qotDtl.push(bidSplrList[m]);
                }
            }
            matinfo[i].qotDtls = qotDtl;
        }
        jQuery("#mygrid3").jqGrid({
            width:'100%',
            dataType:'local',
            width:'100%',
            height: 250,
            colNames:['ID','物料编码','物料名称', '计量单位', '招标数量','交货地址','交货日期','备注'],
            colModel:[
                {name:'id',index:'id', width:50,hidden: true},
                {name:'matCod',index:'matCod', width:80},
                {name:'matNam',index:'matNam', width:150},
                {name:'matUnt',index:'matUnt', width:80,align:"center"},
                {name:'pchsNum',index:'pchsNum', width:80,align:"center"},
                {name:'dlvAdr',index:'dlvAdr', width:80},
                {name:'dlvDte',index:'dlvDte', width:120,align:"center"},
                {name:'memo',index:'memo', width:150}
            ],
            subGrid: true,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            // define the icons in subgrid
            subGridOptions: {
                "plusicon"  : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon"  : "ui-icon-arrowreturn-1-e",
                "reloadOnExpand" : true,
                "selectOnExpand" : true
            },
            subGridRowExpanded: function(subgrid_id, row_id) {
                var subgrid_table_id, pager_id, lastsel;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;
                $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
                jQuery("#"+subgrid_table_id).jqGrid({
                    datatype: "local",
                    height: '100%',
                    colNames: ['matId','供应商ID','供应商','币种','币种hidden','定标价格','定标数量','合计','定标交货日期','品牌','备注'],
                    colModel: [
                        {name:"matId",index:"matId",hidden:true},
                        {name:"splrId",index:"splrId",hidden:true},
                        {name:"splrNam",index:"splrNam",width:200, sortable:false},
                        {name:"currTypFmt",index:"currTypFmt",width:70,align:"center", sortable:false,formatter: currTypFmatter},
                        {name:"currTyp",index:"currTyp",hidden:true},
                        {name:"untPri",index:"untPri",width:100,align:"center", sortable:false},
                        {name:"pchsNum",index:"pchsNum",width:100,align:"center", classes:"splNum",sortable:false},
                        {name:"ttlPri",index:"ttlPri",width:100,align:"center", sortable:false},
                        {name:"tendDlvDte",index:"tendDlvDte",width:130,align:"center", sortable:false},
                        {name:"matBnd",index:"matBnd",width:100,align:"center", sortable:false},
                        {name:"memo",index:"memo",width:100,align:"center", sortable:false}
                    ],
                    fitColumns: true,
                    shrinkToFit: true,
                    altRows: true
                });
                for(var m=0;m<matinfo[row_id-1].qotDtls.length;m++){
                    totalLines+=1;
                    var subrowid = m+1;
                    var rowinfo = matinfo[row_id-1].qotDtls[m];
                    rowinfo.id = subrowid;
                    rowinfo.tendDlvDte = rowinfo.tendDlvDte ? (new Date(rowinfo.tendDlvDte)).Format("yyyy-MM-dd") : '';
                    rowinfo.currTypFmt = rowinfo.currTyp ? rowinfo.currTyp : '';
                    $("#"+subgrid_table_id).jqGrid('addRowData', subrowid, rowinfo);
                    $("#"+subgrid_table_id+" #"+subrowid).data("rowinfo",rowinfo);
                }
            }
        });
        for ( var i = 0; i < matinfo.length; i++){
            var rowid = i+1;
            matinfo[i].dlvDte = matinfo[i].dlvDte ? (new Date(matinfo[i].dlvDte)).Format("yyyy-MM-dd") : '';
            $("#mygrid3").jqGrid('addRowData', rowid, matinfo[i]);
            $("#mygrid3>tbody>tr#"+rowid+">td").trigger("click");  // 报价信息展开
            if($("#mygrid3_"+rowid+"_t").width()+27<$(".mygrid3").width()){
                $("#mygrid3_"+rowid+"_t").jqGrid('setGridWidth', $(".mygrid3").width()-27);
            }
        }
        jQuery("#mygrid3").jqGrid('setGridWidth', $("#mygrid3_1_t").width()+27);
        console.log('totalLines--->',totalLines);
        jQuery("#mygrid3").jqGrid('setGridHeight', totalLines*30+3*(matinfo.length+1));
        $("#mygrid3>tbody>tr.jqgrow").addClass("bg-lightgray");

    }


// 重置grid 大小
    function resetGridTable(){
        var table_id = "mygrid2";
        var ids = $("#"+table_id).jqGrid("getDataIDs");
        for(var i=0;i<ids.length;i++){
            var subgrid_table_id = table_id+"_"+ids[i]+"_t";
            if($("#"+subgrid_table_id).width()+27<$(".qotinfo2").width()){
                $("#"+subgrid_table_id).jqGrid('setGridWidth', $(".qotinfo2").width()-27);
            }
        }
        $("#mygrid2").jqGrid('setGridWidth', $("#mygrid2_1_t").width()+27);
        if($("#mygrid").width()< $(".qotinfo").width()){
            $("#mygrid").jqGrid('setGridWidth', $(".qotinfo").width()-4);
        }
    }

    $(window).resize(function(){
        resetGridTable();
    });
// 获取已选中的数据
    function getPostDatas(){
        var table_id = "mygrid2";
        var ids = $("#"+table_id).jqGrid("getDataIDs");
        var datalist = [];
        for(var i=0;i<ids.length;i++){
            var subgrid_table_id = table_id+"_"+ids[i]+"_t";
            if($("#"+subgrid_table_id).length==0){   // 忽略已经收缩起来的行信息
                continue;
            }
            var subids = $("#"+subgrid_table_id).jqGrid('getGridParam','selarrrow');
            if($("#"+subgrid_table_id)[0].p.savedRow.length){
                $("#"+subgrid_table_id).jqGrid("saveCell", $("#"+subgrid_table_id)[0].p.savedRow[0].id, $("#"+subgrid_table_id)[0].p.savedRow[0].ic)
            }
            var matinfo = $("#mygrid2").jqGrid("getRowData",ids[i]);
            console.log(i,ids[i],matinfo);
            if(subids.length){
                for(var j=0;j<subids.length;j++){
                    $("#"+subgrid_table_id).saveRow(subids[j], false, 'clientArray');
                    var content = $("#"+subgrid_table_id).jqGrid("getRowData",subids[j]);
                    content.matCod = matinfo.matCod;
                    console.log(i,j,content);
                    datalist.push(content);
                }
            }
        }
        var resultList = datalist.concat(colapsedRow);  // 合并已经选择并收缩的数据行信息
        return resultList;
    }

    function rendinfo(){
        var table_id = "mygrid2";
        var ids = $("#"+table_id).jqGrid("getDataIDs");
        for(var i=0;i<ids.length;i++){
            var subgrid_table_id = table_id+"_"+ids[i]+"_t";
            var subids = $("#"+subgrid_table_id).jqGrid('getDataIDs');
            var tmpmatinfo = $("#mygrid2").jqGrid("getRowData",ids[i]);
            for(var j=0;j<subids.length;j++){
                var content = $("#"+subgrid_table_id).jqGrid("getRowData",subids[j]);
                if(tmpmatinfo.dlvDte!=content.tendDlvDte){
                    console.log(subgrid_table_id,tmpmatinfo.dlvDte,content.tendDlvDte);
                    $("#"+subgrid_table_id+" #"+subids[j]).find("td.datetime").addClass("bg-yellow");
                }
                if(tmpmatinfo.pchsNum!=content.splNum){
                    $("#"+subgrid_table_id+" #"+subids[j]).find("td.splNum").addClass("bg-yellow");
                }
            }
        }
    }
});


